package com.xsky.datagrid.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.basic.DateConverter;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.xsky.database.dao.impl.BaseEntityDaoImpl;
import com.xsky.datagrid.facade.IDataGridService;

public class DataGridService implements IDataGridService
{
	public static void main(String[] args)
	{
//		DataGridService ds = new DataGridService();
		System.out.println(new DataGridService().selectById("TabMeetingCenter", "86F4D025-EE6A-BE00-3466-7B079A875FC5"));
	}
	public String genGridTemplate(String tableName)
	{
		try
		{
			TableConfiguration tcf = TableConfiguration.getInstance();
			Table table = tcf.getTable(tableName);
			String tableInfo = table.getXml().asXML();
			String resourceInfo = tcf.genResource();
			return "<data>"+resourceInfo+tableInfo+"</data>";
		} catch (DocumentException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		return null;
	}

//	数据检索
	/* (non-Javadoc)
	 * @see com.xsky.datagrid.facade.IDataGridService#search(java.lang.String)
	 * searchItemXml：格式如下
	 * <data>
	 * <table>tableName</table>
	 * <condition></condition>
	 * </data>
	 */
	public String search(String searchItemXml)
	{
		StringBuffer resultXml = new StringBuffer();
		Document document = null;
		try {
			document = DocumentHelper.parseText(searchItemXml);
		} catch (DocumentException e2) {
			e2.printStackTrace();
		}
		if(document==null)
		{
			return "";
		}
		String tableName = document.selectSingleNode("//data/table").getText();
		String start = document.selectSingleNode("//data/page/start").getText();
		String limit = document.selectSingleNode("//data/page/limit").getText();
		String orderBy = document.selectSingleNode("//data/page/orderBy").getText();
		String orderType = document.selectSingleNode("//data/page/orderType").getText();
		Node conditionNode = document.selectSingleNode("//data/condition");
		String condition = "";
		String fullName = "com.xsky.operation.vo."+tableName;
		if(conditionNode!=null)
		{
			condition = conditionNode.getText();
			if("".equals(condition)||"null".equals(condition))
			{
				condition = "";
			}
		}
		Class entityClass = null;
		try
		{
			entityClass = Class.forName(fullName);
		}
		catch (ClassNotFoundException e)
		{
			e.printStackTrace();
		}
		BaseEntityDaoImpl baseDao = new BaseEntityDaoImpl();
		int totalNumbers = baseDao.fetchCount(fullName, condition);
		List resultList = new ArrayList();
		if("全部".equals(limit))
		{
			resultList = baseDao.fetchAllWithCondition(fullName,condition,orderBy,orderType);
		}
		else
		{
			resultList = baseDao.fetchByPagesWithCondition(fullName, start, limit, condition, orderBy, orderType);
			
		}
		resultXml.append("<root>");
		resultXml.append("<totalRecords>"+totalNumbers+"</totalRecords>");
		resultXml.append("<data>");
		XStream xs = new XStream();
		xs.alias("item", entityClass);
		//xs.registerConverter(new XStreamClobConverter());
		for(int i = 0; i < resultList.size(); i++)
		{
			resultXml.append(xs.toXML(resultList.get(i)));
		}
		resultXml.append("</data>");
		resultXml.append("<result>ok</result>");
		resultXml.append("</root>");
		return resultXml.toString().replace(" 00:00:00.0", "");
	}
	
	public String add(String dataXml)
	{
		StringBuffer resultXml = new StringBuffer();
		Document document;
		String id="";
		try
		{
			document = DocumentHelper.parseText(dataXml);
			String tableName = document.getRootElement().attribute("tableName").getText();
			document.getRootElement().remove(document.getRootElement().attribute("tableName"));
			dataXml = document.asXML();
			String fullName = "com.xsky.operation.vo."+tableName;
			id = document.selectSingleNode("//data/id").getText();
			Class entityClass = null;
			try
			{
				entityClass = Class.forName(fullName);
			}
			catch (ClassNotFoundException e)
			{
				e.printStackTrace();
			}
//		String start = document.selectSingleNode("//data/pa ge/start").getText();
			BaseEntityDaoImpl baseDao = new BaseEntityDaoImpl();
			XStream xs = new XStream(new DomDriver());
			String defaultFormat = "yyyy-MM-dd HH:mm:ss";
			String[] acceptableFormat = {"yyyy-MM-dd HH:mm:ss","yyyy-MM-dd"};
			xs.registerConverter(new DateConverter(defaultFormat,acceptableFormat));
			xs.alias("data", entityClass);
			try
			{
				Object object = xs.fromXML(dataXml);
				baseDao.insertEntity(object);
			}catch(Exception e)
			{
				e.printStackTrace();
			}
		} catch (DocumentException e2)
		{
			e2.printStackTrace();
		}
		return "<info><result>ok</result><id>"+id+"</id><message>提交成功</message></info>";
	}
	public String update(String dataXml) {
		StringBuffer resultXml = new StringBuffer();
		Document document;
		String id="";
		try {
			document = DocumentHelper.parseText(dataXml);
			id = document.selectSingleNode("//data/id").getText();
			String tableName = document.getRootElement().attribute("tableName").getText();
			document.getRootElement().remove(document.getRootElement().attribute("tableName"));
			dataXml = document.asXML();
			String fullName = "com.xsky.operation.vo." + tableName;
			Class entityClass = null;
			try {
				entityClass = Class.forName(fullName);
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
			BaseEntityDaoImpl baseDao = new BaseEntityDaoImpl();
			XStream xs = new XStream(new DomDriver());
			String defaultFormat = "yyyy-MM-dd HH:mm:ss";
			String[] acceptableFormat = { "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd" };
			xs.registerConverter(new DateConverter(defaultFormat,
					acceptableFormat));
			xs.alias("data", entityClass);
			Object object = xs.fromXML(dataXml);
			baseDao.updateEntity(object);
		} catch (DocumentException e2) {
			e2.printStackTrace();
		}
		return "<info><result>ok</result><id>"+id+"</id><message>更新成功</message></info>";
	}
	public String delete(String dataXml)
	{
		Document document;
		try
		{
			BaseEntityDaoImpl baseDao = new BaseEntityDaoImpl();
			document = DocumentHelper.parseText(dataXml);
			String tableName = document.getRootElement().attribute("table").getText();
			ReflectTable reflectTable = null;
			try
			{
				reflectTable = ReflectTable.getInstance();
			} catch (IOException e1)
			{
				e1.printStackTrace();
			}
			String fullName = (String)reflectTable.reflectMap.get(tableName);
			List itemList = document.selectNodes("//data/item");
			for(int i = 0; i < itemList.size(); i++)
			{
				Element element = (Element)itemList.get(i);
				String id = element.selectSingleNode("id").getText();
				if(element.attribute("selected")!=null)
				{
					String isSelected = element.attribute("selected").getText();
					if("true".equals(isSelected))
					{
						baseDao.deleteByKey(fullName, "id", id);
					}
					else
					{
						continue;
					}
				}
				else
				{
					id = "";
					element = null;
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return "删除成功";
	}
	public String deleteById(String tableName, String id)
	{
		BaseEntityDaoImpl baseDao = new BaseEntityDaoImpl();
		ReflectTable reflectTable = null;
		try
		{
			try
			{
				reflectTable = ReflectTable.getInstance();
			} catch (DocumentException e)
			{
				e.printStackTrace();
			}
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		String fullName = (String)reflectTable.reflectMap.get(tableName);
		baseDao.deleteByKey(fullName, "id", id);
		return "删除成功";
	}
	public String selectById(String tableName, String id)
	{
		BaseEntityDaoImpl baseDao = new BaseEntityDaoImpl();
		ReflectTable reflectTable = null;
		try
		{
			try
			{
				reflectTable = ReflectTable.getInstance();
			} catch (DocumentException e)
			{
				e.printStackTrace();
			}
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		String fullName = (String)reflectTable.reflectMap.get(tableName);
		Class entityClass = null;
		try
		{
			entityClass = Class.forName(fullName);
		}
		catch (ClassNotFoundException e)
		{
			e.printStackTrace();
		}
		Object object = new Object();
		object = baseDao.findByPrimaryKey(tableName, "id", id);
		StringBuffer resultXml = new StringBuffer("");
		resultXml.append("<data>");
		XStream xs = new XStream();
		xs.alias("item", entityClass);
		if(object!=null)
		{
			resultXml.append(xs.toXML(object));
		}
		resultXml.append("</data>");
		return resultXml.toString();
	}
	public String genConfig(String configName)
	{
		try
		{
			Config config = Config.getInstance();
			String configStr = (String)config.configMap.get(configName);
			//System.out.println(configStr);
			return configStr;
		} catch (DocumentException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		return null;
	}
	public String genAll(String tableName)
	{
		String fullName = "com.xsky.operation.vo."+tableName;
		Class entityClass = null;
		try
		{
			entityClass = Class.forName(fullName);
		}
		catch (ClassNotFoundException e)
		{
			e.printStackTrace();
		}
		BaseEntityDaoImpl baseDao = new BaseEntityDaoImpl();
		List resultList = baseDao.findAll(fullName);
		StringBuffer resultXml = new StringBuffer("");
		resultXml.append("<data>");
		XStream xs = new XStream();
		xs.alias("item", entityClass);
		//xs.registerConverter(new XStreamClobConverter());
		for(int i = 0; i < resultList.size(); i++)
		{
			resultXml.append(xs.toXML(resultList.get(i)));
		}
		resultXml.append("</data>");
		return resultXml.toString().replace(" 00:00:00.0", "");
	}
	public String genAllByCondition(String tableName,String condition)
	{
		String fullName = "com.xsky.operation.vo."+tableName;
		Class entityClass = null;
		try
		{
			entityClass = Class.forName(fullName);
		}
		catch (ClassNotFoundException e)
		{
			e.printStackTrace();
		}
		BaseEntityDaoImpl baseDao = new BaseEntityDaoImpl();
		List resultList = baseDao.findByHql("from "+tableName+" model where "+condition);
		StringBuffer resultXml = new StringBuffer("");
		resultXml.append("<data>");
		XStream xs = new XStream();
		xs.alias("item", entityClass);
		//xs.registerConverter(new XStreamClobConverter());
		for(int i = 0; i < resultList.size(); i++)
		{
			resultXml.append(xs.toXML(resultList.get(i)));
		}
		resultXml.append("</data>");
		return resultXml.toString().replace(" 00:00:00.0", "");
	}
}
